﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using MediaArtAggregator.Core.Configuration;

namespace MediaArtAggregator.Core.SearchProvider {
  [XmlRoot ( "source" )]
  public class RegexBasedSearchSource : SearchSource {

    [XmlElement ( "base" )]
    public string BaseUrl { get; set; }
    [XmlElement ( "url" )]
    public string SearchFormat { get; set; }
    [XmlElement ( "pattern" )]
    public string Pattern { get; set; }
    [XmlElement ( "referer" )]
    public string Referer { get; set; }

    public override void Search ( string search, Settings settings, SearchType searchType ) {
      this.OnSearchInitialize ( EventArgs.Empty );

      HttpWebRequest req = HttpWebRequest.Create ( string.Format (
        string.Format ( "{0}{1}", this.BaseUrl, this.SearchFormat ),
        Utilities.GetSafeSearchString (search), 
        string.IsNullOrEmpty(searchType.Value) ? string.Empty : Utilities.GetSafeSearchString (searchType.Value) ) 
      ) as HttpWebRequest;
      req.UserAgent = settings.UserAgent;
      req.Referer = this.Referer;

      HttpWebResponse resp = req.GetResponse ( ) as HttpWebResponse;
      StreamReader reader = new StreamReader ( resp.GetResponseStream ( ) );
      StringBuilder data = new StringBuilder ( );
      using ( reader ) {
        while ( !reader.EndOfStream ) {
          data.Append ( reader.ReadLine ( ) );
        }
      }

      Regex regex = new Regex ( this.Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline );
      Match match = regex.Match ( data.ToString ( ) );
      while ( match.Success ) {
        Uri url = new Uri ( match.Groups[ 1 ].Value );
        this.Results.Add ( url );
        match = match.NextMatch ( );
      }

      this.OnSearchComplete ( EventArgs.Empty );
    }

    public override string ToString ( ) {
      return new Uri ( this.BaseUrl ).Host;
    }
  }
}
